<template>
  <el-row>
    <el-col :span="24">

      <el-form ref="queryForm" :model="queryParams" :inline="true" size="medium" @submit.prevent.native>
        <el-form-item :label="$t('科目名称')" prop="keyName">
          <el-input
            v-model="queryParams.keyName"
            :placeholder="$t('科目名称')"
            clearable
            :onsubmit="false"
            @keyup.enter.native="queryHandle"
          />
        </el-form-item>
        <el-form-item :label="$t('关注科目')" prop="focusOn">
          <!-- <el-select v-model="queryParams.focusOn" :placeholder="$t('关注科目')" clearable>
            <el-option
              v-for="item in focusOnOptions"
              :key="item.keyCode"
              :label="item.keyName"
              :value="item.keyName"
            />
          </el-select> -->
          <el-radio-group v-model="focusKeys" size="mini" @input="focusName">
            <el-radio-button label="全部" />
            <el-radio-button label="关注" />
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        </el-form-item>
      </el-form>

      <el-table ref="scrollTable" v-loading="loading" :data="tableData" border max-height="550" height="550" @paste.native="onPaste">
        <el-table-column :label="$t('序号')" type="index" align="center" />
        <el-table-column :label="$t('科目名称')" align="center" prop="subjectName" min-width="200">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949; margin-right: 4px">*</i>
            <span>{{ $t("科目名称") }}</span>
          </template>
          <template v-slot="scope">
            <template v-if="contain(scope.row) === 'warning'">
              <el-tag size="mini" class="small-tag" effect="dark" type="warning" style="cursor: pointer" @click="returnMatchingStr(scope.row)">
                <el-popover
                  placement="top-start"
                  title="以下系统科目与财报科目类似，供您参考"
                  trigger="hover"
                  :content="`${returnMatching(scope.row.subjectName)}`"
                >
                  <i slot="reference" class="el-icon-question" />
                </el-popover>
              </el-tag>
            </template>
            <template v-else-if="contain(scope.row) === 'success'">
              <el-tag size="mini" class="small-tag" effect="dark" type="success"> <i class="el-icon-success" /></el-tag>
            </template>
            <template v-else>
              <el-tag size="mini" class="small-tag" effect="dark" type="danger"> <i class="el-icon-error" /></el-tag>
            </template>
            <el-autocomplete v-model="scope.row.subjectName" :fetch-suggestions="querySearch" show-word-limit :maxlength="100" :placeholder="$t('科目名称')" style="width: 96%" @focus="calcRatio" />
          </template>

        <!-- :class="contain(scope.row.subjectName) ? '' : 'font-color-red'" -->
        </el-table-column>
        <el-table-column :label=" $t('金额(元)')" align="center" prop="amount1" width="300">
          <template v-slot="scope">
            <money v-model="scope.row.amount1" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="50">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="deleteHandle(scope.row,scope.$index)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-dropdown size="mini" split-button type="primary" @command="handleCommand" @click="addSubject(1)">
          {{ $t('添加') }}<i class="el-icon-plus el-icon--right" />
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="5">{{ $t('添加5行') }}</el-dropdown-item>
            <el-dropdown-item command="10">{{ $t('添加10行') }}</el-dropdown-item>
            <el-dropdown-item command="20">{{ $t('添加20行') }}</el-dropdown-item>
            <el-dropdown-item command="30">{{ $t('添加30行') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <el-checkbox v-model="enableCopyExcel" style="margin-left: 10px;">批量修改-开启后可复制粘贴Excel数据</el-checkbox> -->
      </div>
      <div class="bottom_contain">
        <div class="tag_contain">
          <el-tag class="small-tag" effect="dark" type="success" size="mini"><i class="el-icon-success" /></el-tag>已匹配科目
          <el-tag class="small-tag" effect="dark" type="warning" size="mini"><i class="el-icon-question" /></el-tag>待确认科目
          <el-tag class="small-tag" effect="dark" type="danger" size="mini"><i class="el-icon-error" /></el-tag>无匹配科目
        </div>
        <!-- <div id="main" style="width:70px;height:70px" /> -->
        <pcwChartRatio ref="pcwChartRatio" :chart-data="matchingStatusRatio" :matching-ratio="matchingRatio" />
      </div>

    </el-col>
  </el-row>
</template>

<script>
import {
  findSubjectNameByCompanyId,
  delDataBaseById,
  findFocusOnSubject
} from '@/api/company/pcw/pcwTempSubject'
import PcwChartRatio from '@/views/company/pcw/pcwChartRatio'
export default {
  name: 'HandEnter',
  components: {
    PcwChartRatio
  },
  props: {
    sheetData: {
      type: Object,
      default: () => {}
    },
    type: {
      type: String,
      default: undefined
    },
    companyId: {
      type: String,
      required: true
    },
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      tableData: [],
      tempSubject: [], // 模板科目
      tempSubjectName: [], // 模板科目名字相似度用到的
      enableCopyExcel: false,
      matchingRatio: 0, // 已匹配科目百分比
      matchingStatusRatio: {
        success: 0,
        warning: 0,
        danger: 0
      },
      subjectRule: {
        subjectName: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }]
      },
      clipboard: '',
      selectedCell: null,
      loading: false,
      queryParams: {
        keyName: undefined,
        focusOn: undefined
      },
      focusOnOptions: [],
      cacheTable: [],
      focusKeys: '全部',
      htmlLoading: true
    }
  },
  watch: {
    // tableData: {
    //   // immediate: true,
    //   handler() {
    //     this.$nextTick(() => {
    //       this.scrollToBottom()
    //     })
    //   }
    // },
     // 监听剪贴板变化
    clipboard(val) {
      console.log('clipboard:', val)
    }
  },
  mounted() {
    //  this.initAddSubject()
    this.htmlLoading = false
    this.$nextTick(() => {
      setTimeout(this.calcRatio, 800)
    })
  },
  created() {
    console.log('this.sheetData', this.sheetData)
    // 查询对应的科目
    this.loading = true
    findSubjectNameByCompanyId(this.companyId, this.type).then(res => {
      this.tempSubject = res.data.map(item => {
        return {
          'value': item
        }
      })
      this.tempSubjectName = res.data
      this.initAddSubject()
      this.cacheTable = this.tableData
      findFocusOnSubject(this.companyId, this.type).then(res => {
        const keyNameValues = res.data.map((option) => option.keyName)
        this.focusOnOptions = keyNameValues
        this.loading = false
      })
    })
  },
  methods: {
    init() {
      this.tableData = this.sheetData.sheetData
      this.cacheTable = this.tableData
      if (this.tableData) {
        this.tableData.map(e => {
          this.contain(e)
        })
      } else {
        this.matchingRatio = 0
      }
    },
    scrollToBottom() {
      const tableBody = this.$refs.scrollTable.$el.querySelector('.el-table__body-wrapper')
      tableBody.scrollTop = tableBody.scrollHeight - tableBody.clientHeight
    },
    deleteHandle(row, index) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return true
        }).then(() => {
          delDataBaseById(row.id)
          this.tableData.splice(index, 1)
          this.calcRatio()
          return this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {})
      } else {
        this.tableData.splice(index, 1)
        this.calcRatio()
        // return this.msgSuccess(this.$t('删除成功'))
      }
    },
    querySearch(queryString, cb) {
      // 对应模板的科目列表
      var restaurants = this.tempSubject
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    contain(row) {
      const val = row.subjectName
      const matchStr = this.returnMatching(val)
      if (matchStr === '') {
        // 记录当前行匹配科目状态
        row['matchStatus'] = 'danger'
        return 'danger'
      }
      // 如果输入的科目是模板里的
      if (this.isStringSimilar(val, matchStr)) {
        row['matchStatus'] = 'warning'
        return 'warning'
      } else {
        const f = this.tempSubject.filter(item => {
          return item.value === val
        }).length > 0
        row['matchStatus'] = f ? 'success' : 'danger'
        return f ? 'success' : 'danger'
      }
    },
    // 添加科目
    addSubject(num) {
      for (let index = 0; index < num; index++) {
        const subject = {
          subjectName: undefined,
          amount1: undefined,
          matchStatus: 'danger'
        }
        this.tableData.push(subject)
      }
       this.scrollToBottom()
    },
    handleCommand(command) {
      command = parseInt(command)
      this.addSubject(command)
    },
    findMostSimilarCourse(targetString) {
      let maxSimilarity = 0
      let mostSimilarCourse = ''
      if (!targetString) {
        return mostSimilarCourse
      }
      for (let i = 0; i < this.tempSubjectName.length; i++) {
        const similarity = this.compareTwoStrings(this.tempSubjectName[i], targetString)
        if (similarity > maxSimilarity) {
          maxSimilarity = similarity
          mostSimilarCourse = this.tempSubjectName[i]
        }
      }
      return mostSimilarCourse
    },
    compareTwoStrings(str1, str2) {
      str1 = str1.replace(/\s+/g, '')
      str2 = str2.replace(/\s+/g, '')

      if (!str1.length && !str2.length) return 1
      if (!str1.length || !str2.length) return 0
      if (str1 === str2) return 1
      if (str1.length === 1 && str2.length === 1) return 0
      if (str1.length < 2 || str2.length < 2) return 0

      const firstBigrams = new Map()
      for (let i = 0; i < str1.length - 1; i++) {
        const bigram = str1.substr(i, 2)
        const count = firstBigrams.has(bigram)
          ? firstBigrams.get(bigram) + 1
          : 1

        firstBigrams.set(bigram, count)
      }

      let intersectionSize = 0
      for (let i = 0; i < str2.length - 1; i++) {
        const bigram = str2.substr(i, 2)
        const count = firstBigrams.has(bigram)
          ? firstBigrams.get(bigram)
          : 0

        if (count > 0) {
          firstBigrams.set(bigram, count - 1)
          intersectionSize++
        }
      }
      return (2.0 * intersectionSize) / (str1.length + str2.length - 2)
    },
    returnMatching(val) {
      return this.findMostSimilarCourse(val)
    },
    returnMatchingStr(row) {
      row.subjectName = this.findMostSimilarCourse(row.subjectName)
    },
    isStringSimilar(str1, str2, threshold = 0.3) {
      if (!str1 || !str2) {
        return false
      }
      str1 = str1.replace(/\s+/g, '')
      str2 = str2.replace(/\s+/g, '')

      if (!str1.length || !str2.length) return false
      const similarity = this.compareTwoStrings(str1, str2)
      return (similarity > threshold && similarity < 1)
    },
    calcRatio() { // 计算 匹配，待确认，无匹配百分比
      const success = this.tableData.filter(item => item.matchStatus === 'success')
      const warning = this.tableData.filter(item => item.matchStatus === 'warning')
      const danger = this.tableData.filter(item => item.matchStatus === 'danger')
      this.matchingStatusRatio.success = success ? success.length : 0
      this.matchingStatusRatio.warning = warning ? warning.length : 0
      this.matchingStatusRatio.danger = danger ? danger.length : 0
      // 计算百分比
      const totalCount = this.matchingStatusRatio.success + this.matchingStatusRatio.warning + this.matchingStatusRatio.danger
      const successRatio = (this.matchingStatusRatio.success / totalCount) * 100
      if (typeof successRatio === 'number' && !isNaN(successRatio)) {
        this.matchingRatio = Math.ceil(successRatio)
      } else {
        this.matchingRatio = 0
      }
      // this.initCharts()
    },
     onPaste(event) {
      if (this.enableCopyExcel) {
          // 阻止默认粘贴行为
          event.preventDefault()
          // 获取粘贴板数据
          const clipboardData = event.clipboardData || window.clipboardData
          // 获取粘贴板中的文本数据
          const pastedData = clipboardData.getData('text')
          const rows = pastedData.split('\n').map(row => row.split('\t'))
          // 遍历表格数据行
          if (this.checkIfAllSubjectNameEmpty()) {
               this.tableData = rows.map(([subjectName, amount1]) => ({ subjectName, amount1 }))
          } else {
              rows.forEach(([subjectName, amount1]) => {
                this.tableData.push({ subjectName, amount1 })
              })
          }
          this.calcRatio()
      }
    },
     checkIfAllSubjectNameEmpty() {
        return this.tableData.every(item => item.subjectName === '' || item.subjectName === undefined)
    },
    initAddSubject() {
      if (this.isAdd) {
        this.tableData = []
        this.tempSubjectName.map(e => {
            const subject = {
              subjectName: e,
              amount1: undefined,
              matchStatus: 'success'
            }
            this.tableData.push(subject)
        })
        // this.addSubject(10)
        // this.tableData.map(e => {
        //   this.contain(e)
        // })
        // this.calcRatio()
     }
    },
    queryHandle() {
     const keyName = this.queryParams.keyName
      if (keyName) {
         this.tableData = this.cacheTable
         this.tableData = this.tableData.filter(item => item.subjectName.includes(keyName))
      } else {
          this.tableData = this.cacheTable
      }
    },
    resetQuery() {
      this.queryParams = {
        keyName: undefined,
        focusOn: undefined
      }
      this.tableData = this.cacheTable
    },
     focusName(name) {
      console.log('this.cacheTable', this.cacheTable)
         if (name === '关注') {
              const filteredTableData = this.filterArrayData(this.cacheTable, 'subjectName', this.focusOnOptions)
              this.tableData = filteredTableData
         } else {
            // 展示全部
            this.tableData = this.cacheTable
         }
      },
      filterArrayData(data, keyName, searchValue) {
        const filteredData = data.filter((item) => {
          return searchValue.includes(item[keyName])
        })
        return filteredData
      }
  }
}
</script>

<style scoped>
.font-color-red /deep/.el-input__inner {
  color: red
}

/* .small-tag {
  height: 18px;
  line-height: 16px;
  padding: 0px 2px;
  font-size: 5px;
  width: 18px;
} */

.tag_contain {
  margin: 24px 0px;
}

.bottom_contain {
  display: flex;
  justify-content: space-between;
}
</style>
